<template>
  <div>
    <div class="el-container">
      <el-descriptions border direction="vertical">
        <el-descriptions-item label="剩余标记："
          ><el-tag>{{ signLeft }}</el-tag></el-descriptions-item
        >
        <el-descriptions-item label="打开计数："
          ><el-tag>{{ openedCount }}</el-tag></el-descriptions-item
        >
        <el-descriptions-item label="游戏状态：">
          <i
            :class="{
              'el-icon-star-on': !isGameOver,
              'el-icon-star-off': isGameOver,
            }"
          ></i>
        </el-descriptions-item>
      </el-descriptions>

      <el-form ref="setting" :model="setting" :rules="rules" label-width="auto">
        <el-form-item label="雷的宽度：" prop="boomLength">
          <el-input-number
            v-model="setting.boomLength"
            controls-position="right"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="雷的个数：" prop="boomNum">
          <el-input-number
            v-model="setting.boomNum"
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>

      <!--      剩余标记：<el-input-number-->
      <!--        disabled-->
      <!--        controls-position="right"-->
      <!--        :value="signLeft"-->
      <!--      ></el-input-number>-->
      <!--      打开计数：<el-input-number-->
      <!--        disabled-->
      <!--        controls-position="right"-->
      <!--        v-model="openedCount"-->
      <!--      ></el-input-number>-->

      <el-button type="info" round @click="() => $refs.setting.resetFields()"
        >清空重置</el-button
      >

      <el-button round type="primary" @click="safetyGenerate"
        >生成一局</el-button
      >
      <el-button round type="warning" @click="scoreVisible = true"
        >历史记录</el-button
      >
    </div>

    <div class="boom-group">
      <template v-for="(e, i) in booms">
        <div class="boom-line" :key="i">
          <template v-for="(cell, j) in e">
            <div class="boom-cell" :key="j">
              <el-button
                :disabled="isGameOver"
                @click="() => leftClick(i, j)"
                @contextmenu.native.prevent="() => rightClick(i, j)"
                class="cell-button"
                :type="cellType(cell)"
                >{{ cellValue(cell) }}</el-button
              >
            </div>
          </template>
        </div>
      </template>
    </div>
    <el-drawer :visible.sync="scoreVisible">
      <!--      <span>{{ scores.length }}</span>-->
      <!--      <span>{{ JSON.stringify(scores) }}</span>-->

      <el-table :data="scores" border>
        <el-table-column
          prop="boomNum"
          label="雷的个数"
          width="108"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="boomLength"
          label="棋盘宽度"
          width="108"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="winTime"
          label="nice获胜时间"
          :formatter="timeFormat"
        ></el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>
<script>
/**
 * 页面核心数据结构体说明文档
 *
 * score: {
        winTime: "2021-03-02",
        boomLength: 0,
        boomNum: 0,
      },
 */
const closedS = "closed";
const openedS = "opened";
// import New from './components/New.vue';
export default {
  name: "Mine3View",
  components: {
    // New,Old,
  },
  props: {
    sampleP: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      sampleD: "value",
      scores: [],
      scoreVisible: false,
      setting: {
        boomLength: 4,
        boomNum: 2,
      },
      rules: {
        boomLength: [
          { validator: this.validateBoomLength, trigger: ["change", "blur"] },
        ],
        boomNum: [
          { validator: this.validateBoomNum, trigger: ["change", "blur"] },
        ],
      },
      // boomLength: 8,
      // boomNum: 10,
      isGameOver: false,
      openedCount: 0,
      signedCount: 0,
      booms: [
        [
          { value: 0, state: closedS, i: 0, j: 0 },
          { value: 0, state: openedS, i: 0, j: 0 },
          { value: 9, state: "signed", i: 0, j: 0 },
          { value: 0, state: "closed", i: 0, j: 0 },
        ],
        [
          { value: 0, state: "closed", i: 0, j: 0 },
          { value: 9, state: "opened", i: 0, j: 0 },
          { value: 9, state: "signed", i: 0, j: 0 },
          { value: 0, state: "closed", i: 0, j: 0 },
        ],
      ],
    };
  },
  computed: {
    signLeft() {
      return this.setting.boomNum - this.signedCount;
    },
    cellType() {
      // return cell.state === 'closed' ? 'info' : null
      return function (cell) {
        // return cell.state === "closed" ? "info" : null;
        switch (cell.state) {
          case "opened":
            if (cell.value === 9) {
              return "danger";
            }
            return null;
          case "closed":
            return "info";
          case "signed":
            return "warning";
          default:
            return "primary";
        }
      };
    },
    cellValue() {
      return function (cell) {
        // return cell.state === "closed" ? null : cell.value;
        switch (cell.state) {
          case "opened":
            return cell.value;
          case "closed":
            return "";
          case "signed":
            return "#";
          default:
            return "";
        }
      };
    },
  },
  created() {},
  mounted() {
    let s = localStorage.getItem("clever:booms:cores");
    if (s) {
      this.scores = JSON.parse(s);
    } else {
      this.scores = [];
    }
    this.safetyGenerate();
  },
  methods: {
    sampleM() {},

    timeFormat(row) {
      // return row.winTime.split("T")[0];
      return row.winTime;
    },
    validateBoomNum(rule, value, toReturn) {
      // console.log(value, this.setting.boomNum);
      if (this.setting.boomNum < 0) {
        toReturn(new Error("雷的个数不能小于0"));
      } else if (this.setting.boomNum >= Math.pow(this.setting.boomLength, 2)) {
        toReturn(new Error("雷的个数不能比雷区总数多"));
      } else {
        toReturn();
      }
    },
    validateBoomLength(rule, value, toReturn) {
      if (this.setting.boomLength < 0 || this.setting.boomLength > 20) {
        toReturn(new Error("宽度介于0-20之间"));
      } else {
        toReturn();
      }
    },

    leftClick(i, j) {
      // console.log("正在打开....", i, j);
      // A B C D  A-B C-A
      if (this.booms[i][j].state === "closed") {
        this.closedToOpened(i, j);
      } else if (this.booms[i][j].state === "opened") {
        this.openedToOpened(i, j);
      }
    },
    rightClick(i, j) {
      // console.log("右键打开。。。", i, j);
      if (this.booms[i][j].state === "closed") {
        this.closedToSigned(i, j);
      } else if (this.booms[i][j].state === "signed") {
        this.signedToClosed(i, j);
      }
    },
    closedToSigned(i, j) {
      if (this.booms[i][j].state !== "closed") {
        return;
      }
      this.booms[i][j].state = "signed";
      this.signedCount++;
    },
    signedToClosed(i, j) {
      if (this.booms[i][j].state !== "signed") {
        return;
      }
      this.booms[i][j].state = "closed";
      this.signedCount--;
    },
    openedToOpened(i, j) {
      let cur = this.booms[i][j];
      if (cur.state !== "opened") {
        return;
      }
      cur.state = "opened";
      console.log("开始。。。");
      //遍历九宫格 如果是标记就计数增加，如果是关闭就暂存，之后点击打开。
      let countS = 0;
      let closedTempArray = [];
      for (let k = -1; k <= 1; k++) {
        for (let l = -1; l <= 1; l++) {
          if (k === 0 && l === 0) {
            continue;
          }
          if (this.booms[i + k] && this.booms[i + k][j + l]) {
            if (this.booms[i + k][j + l].state === "signed") {
              countS++;
            }
            if (this.booms[i + k][j + l].state === "closed") {
              closedTempArray.push(this.booms[i + k][j + l]);
            }
          }
        }
      }
      if (countS && countS === cur.value) {
        for (let closedCell of closedTempArray) {
          setTimeout(() => {
            this.leftClick(closedCell.i, closedCell.j);
          }, 200);
        }
      }
    },

    closedToOpened(i, j) {
      let cur = this.booms[i][j];
      if (cur.state !== "closed") {
        return;
      }
      //点开雷爆炸 游戏结束
      cur.state = "opened";
      if (cur.value === 9) {
        this.lose();

        return;
      }
      //点开数量够多 胜利 游戏结束
      this.openedCount++;
      if (
        this.openedCount + this.setting.boomNum >=
        Math.pow(this.setting.boomLength, 2)
      ) {
        this.win();

        return;
      }
      //  0个雷时候 帮助用户点击九宫格
      if (cur.value === 0) {
        for (let k = -1; k <= 1; k++) {
          for (let l = -1; l <= 1; l++) {
            if (k === 0 && l === 0) {
              continue;
            }
            //先判断数组无越界 再判断当前处于关闭状态
            if (this.booms[i + k] && this.booms[i + k][j + l]) {
              if (this.booms[i + k][j + l].state === "closed") {
                //  点击按钮打开
                setTimeout(() => {
                  this.leftClick(i + k, j + l);
                }, 200);
              }
            }
          }
        }
      }
    },
    safetyGenerate() {
      this.$refs.setting.validate((valid) => {
        if (valid) {
          this.generate();
        } else {
          this.$message.warning("验证不通过请重新填写表单");
        }
      });
    },
    generate() {
      // this.$message.success("hi");
      //  生成数组初始化0
      let q = [];
      let boomLength = this.setting.boomLength;
      let boomNum = this.setting.boomNum;
      for (let i = 0; i < boomLength; i++) {
        q[i] = [];
        for (let j = 0; j < boomLength; j++) {
          q[i][j] = { value: 0, state: "closed", i: i, j: j };
        }
      }
      //生成随机雷
      for (let number = 0; number < boomNum; ) {
        let m = Math.floor(Math.random() * boomLength);
        let n = Math.floor(Math.random() * boomLength);
        if (q[m][n].value === 9) {
          continue;
        }
        q[m][n].value = 9;
        number++;
      }
      //九宫格计数。
      // (1,1)

      for (let i = 0; i < boomLength; i++) {
        for (let j = 0; j < boomLength; j++) {
          // q[i][j]如果当前九宫格核心是雷 则跳过
          if (q[i][j].value === 9) {
            continue;
          }
          //循环计数
          let count = 0;
          for (let k = -1; k <= 1; k++) {
            for (let l = -1; l <= 1; l++) {
              if (k === 0 && l === 0) {
                continue;
              }
              //如果是雷 就计数
              if (q[i + k] && q[i + k][j + l]) {
                if (q[i + k][j + l].value === 9) {
                  count++;
                }
              }
            }
          }
          q[i][j].value = count;
        }
      }

      console.log(q);
      this.booms = q;

      this.isGameOver = false;
      this.openedCount = 0;
      this.signedCount = 0;
    },
    win() {
      this.$message.success("清空雷区，游戏获胜");
      this.isGameOver = true;
      if (this.scores.length >= 8) {
        this.scores.shift();
      }
      this.scores.push({
        winTime: new Date().toJSON(),
        boomLength: this.setting.boomLength,
        boomNum: this.setting.boomNum,
      });
    },
    lose() {
      this.$message.error("触发雷区，游戏失败");
      this.isGameOver = true;
    },
  },
  watch: {
    // sampleC(newValue, oldValue) {
    //
    // }
    scores(n) {
      // console.log("观测到变化了");
      // console.log(n);
      // console.log(o);
      localStorage.setItem("clever:booms:cores", JSON.stringify(n));
      console.log(this.scores);
    },
  },
};
</script>

<!--<style scoped>-->
<style lang="scss" scoped>
.boom-group {
  //border: 10px solid red;
  display: flex;
  flex-direction: column;
  margin-left: 200px;
}
.boom-line {
  //border: 4px solid blue;
  display: flex;
  flex-direction: row;
  padding: 4px;
}
.boom-cell {
  padding: 0 4px;
}
.cell-button {
  min-width: 64px;
  min-height: 64px;
  font-size: 22px;
}
.el-form {
  width: 300px;
  margin-left: 100px;
}
.el-descriptions {
  width: 300px;
  margin-left: 200px;
}
.el-container {
  align-items: start;
}
</style>
